/**
 * 
 *  V2 版本  可亮度台灯 lamb_mqtt.c 支持云端、机器人双通道控制
 * 每台互联设备 对应fan_mqtt.c door_mqtt.c  lamb_mqtt.c  water_mqtt.c 编译记得修改 BUILD.gn
 * data:2022.05.30 HelloKun 优化-可调亮度
 * */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"

#include "wifi_connect.h"
#include "MQTTClient.h"

#include "wifiiot_errno.h"
#include "wifiiot_gpio.h"
#include "wifiiot_gpio_ex.h"
#include "wifiiot_adc.h"
#include "wifiiot_uart.h"
#include "wifiiot_pwm.h"
#include "hi_uart.h"

#define UART_BUFF_SIZE 1000
#define MQTT_BUFF_SIZE 1000

static const char *data = "MRobot_lamb\r\n";
uint8_t uart_buff[UART_BUFF_SIZE] = {0};
uint8_t *uart_buff_ptr = uart_buff;
char mqtt_buff[MQTT_BUFF_SIZE] = {0};
char lamb_union_data[30] = {0};
static unsigned char sendBuf[1000];
static unsigned char readBuf[1000];


Network network;

void messageArrived(MessageData *data)
{
	printf("Message arrived on topic %.*s: %.*s\n", data->topicName->lenstring.len, data->topicName->lenstring.data,
		   data->message->payloadlen, data->message->payload);
	strcpy(mqtt_buff, data->message->payload);
	printf("mqtt_buff%s \n", mqtt_buff);
}

/************* MRobotUnionDevices Control ******************/
// GPIO 接口与原理图对应  使用哪个就在主函数加入Init、 Ctr函数。

static void MyUartInit(void)
{
	uint32_t ret;
	WifiIotUartAttribute uart_attr = {
		.baudRate = 115200,

		// data_bits: 8bits
		.dataBits = 8,
		.stopBits = 1,
		.parity = 0,
	};

	// Initialize uart driver
	ret = UartInit(WIFI_IOT_UART_IDX_1, &uart_attr, NULL);
	if (ret != WIFI_IOT_SUCCESS)
	{
		printf("Failed to init uart! Err code = %d\n", ret);
		return;
	}
}

/**********************Lamb**********************/
static void LambInit(void)
{
	//初始化GPIO
	GpioInit();
	IoSetFunc(WIFI_IOT_IO_NAME_GPIO_2, WIFI_IOT_IO_FUNC_GPIO_2_PWM2_OUT);
	GpioSetDir(WIFI_IOT_IO_NAME_GPIO_2, WIFI_IOT_GPIO_DIR_OUT);
	PwmInit(WIFI_IOT_PWM_PORT_PWM2);
	PwmStart(WIFI_IOT_PWM_PORT_PWM2, 40000, 40000);
}

static void LambCtr(void)
{
	//UartRead(WIFI_IOT_UART_IDX_1, uart_buff_ptr, UART_BUFF_SIZE);
	hi_uart_read_timeout(WIFI_IOT_UART_IDX_1, uart_buff_ptr, UART_BUFF_SIZE, 10);
	printf("Uart1 read lamb data:%s \n", uart_buff_ptr);
	if ((uart_buff[0] == '3' && uart_buff[1] == '1') || (mqtt_buff[0] == '3' && mqtt_buff[1] == '1'))
	{
		printf("******* Trun On Lamb lev-1 *****\n");
		PwmStart(WIFI_IOT_PWM_PORT_PWM2, 15000, 40000);
		uart_buff[0] = '5';
		mqtt_buff[0] = '5'; //解耦 -防止两个通道互相干扰
		return;
	}
	if ((uart_buff[0] == '3' && uart_buff[1] == '2') || (mqtt_buff[0] == '3' && mqtt_buff[1] == '2'))
	{
		printf("******* Trun On Lamb lev-2*****\n");
		PwmStart(WIFI_IOT_PWM_PORT_PWM2, 25000, 40000);
		uart_buff[0] = '5';
		mqtt_buff[0] = '5';
		return;
	}
	if ((uart_buff[0] == '3' && uart_buff[1] == '3') || (mqtt_buff[0] == '3' && mqtt_buff[1] == '3'))
	{
		printf("******* Trun On Lamb lev-3 *****\n");
		PwmStart(WIFI_IOT_PWM_PORT_PWM2, 40000, 40000);
		uart_buff[0] = '5';
		mqtt_buff[0] = '5';
		return;
	}

	if ((uart_buff[0] == '3' && uart_buff[1] == '0') || (mqtt_buff[0] == '3' && mqtt_buff[1] == '0'))
	{
		printf("******* Trun Off Lamb *****\n");
		PwmStop(WIFI_IOT_PWM_PORT_PWM2);
		uart_buff[0] = '5';
		mqtt_buff[0] = '5';
		return;
	}
	//fan
	if (uart_buff[0] == '1' && uart_buff[1] == '0')
	{
		uart_buff[0] = '5';
		strcpy(lamb_union_data, "turn off fan");
		printf("turn off fan \n");
		return;
	}
	if (uart_buff[0] == '1' && uart_buff[1] == '1')
	{
		uart_buff[0] = '5';
		strcpy(lamb_union_data, "turn on fan lev1");
		printf("turn on fan lev1 \n");
		return;
	}
	if (uart_buff[0] == '1' && uart_buff[1] == '2')
	{
		uart_buff[0] = '5';
		strcpy(lamb_union_data, "turn on fan lev2");
		printf("turn on fan lev2 \n");
		return;
	}
	if (uart_buff[0] == '1' && uart_buff[1] == '3')
	{
		uart_buff[0] = '5';
		strcpy(lamb_union_data, "turn on fan lev3");
		printf("turn on fan lev3 \n");
		return;
	}

	//door
	if (uart_buff[0] == '2' && uart_buff[1] == '1')
	{
		uart_buff[0] = '5';
		strcpy(lamb_union_data, "open door");
		printf("open door \n");
		return;
	}

	//lamb
	if (uart_buff[0] == '3' && uart_buff[1] == '0')
	{
		uart_buff[0] = '5';
		strcpy(lamb_union_data, "turn off lamb");
		printf("turn off lamb \n");
		return;
	}
	if (uart_buff[0] == '3' && uart_buff[1] == '1')
	{
		uart_buff[0] = '5';
		strcpy(lamb_union_data, "turn on lamb lev1");
		printf("turn on lamb lev1 \n");
		return;
	}
	if (uart_buff[0] == '3' && uart_buff[1] == '2')
	{
		uart_buff[0] = '5';
		strcpy(lamb_union_data, "turn on lamb lev2");
		printf("turn on lamb lev2 \n");
		return;
	}
	if (uart_buff[0] == '3' && uart_buff[1] == '3')
	{
		uart_buff[0] = '5';
		strcpy(lamb_union_data, "turn on lamb lev3");
		printf("turn on lamb lev3 \n");
		return;
	}

	//water
	if (uart_buff[0] == '4' && uart_buff[1] == '1')
	{
		uart_buff[0] = '5';
		strcpy(lamb_union_data, "go ahead water");
		printf("go ahead water \n");
		return;
	}
	return;
}

static void MQTT_LambTask(void)
{
	MyUartInit();
	LambInit();
	WifiConnect("r1", "88888889");
	printf("Starting ...\n");
	int rc, count = 0;
	MQTTClient client;

	NetworkInit(&network);
	printf("NetworkConnect  ...\n");

begin:
	NetworkConnect(&network, "120.55.170.12", 1883); // hellokun.cn
	printf("MQTTClientInit  ...\n");
	MQTTClientInit(&client, &network, 2000, sendBuf, sizeof(sendBuf), readBuf, sizeof(readBuf));

	MQTTString clientId = MQTTString_initializer;
	clientId.cstring = "MRobot_lamb";

	MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
	data.clientID = clientId;
	data.willFlag = 0;
	data.MQTTVersion = 3;
	data.keepAliveInterval = 0;
	data.cleansession = 1;

	printf("MQTTConnect  ...\n");
	rc = MQTTConnect(&client, &data);
	if (rc != 0)
	{
		printf("MQTTConnect: %d\n", rc);
		NetworkDisconnect(&network);
		MQTTDisconnect(&client);
		osDelay(200);
		goto begin;
	}

	printf("MQTTSubscribe  ...\n");
	//其他设备 web_fan_btn web_door_btn  web_water_btn

	rc = MQTTSubscribe(&client, "web_lamb_btn", 2, messageArrived); //回调
	if (rc != 0)
	{
		printf("MQTTSubscribe: %d\n", rc);
		osDelay(200);
		goto begin;
	}
	while (++count)
	{
		//使用哪个设备就在加入对应Init、 Ctr。
		LambCtr();

		MQTTMessage message;
		char payload[30];

		message.qos = 2;
		message.retained = 0;
		message.payload = payload;
		sprintf(payload, "%s", lamb_union_data);
		message.payloadlen = strlen(payload);

		osDelay(30);
		if ((rc = MQTTPublish(&client, "lamb_union", &message)) != 0)
		{
			printf("Return code from MQTT publish is %d\n", rc);
			NetworkDisconnect(&network);
			MQTTDisconnect(&client);
			goto begin;
		}
		osDelay(50);

		printf("----- count = %d ------\r\n", count);
		if (count > 1000)
		{
			count = 1;
		}
		strcpy(lamb_union_data,"Niubility for Lamb");
	}
}
static void MQTT_Lamb(void)
{
	osThreadAttr_t attr;

	attr.name = "MQTT_LambTask";
	attr.attr_bits = 0U;
	attr.cb_mem = NULL;
	attr.cb_size = 0U;
	attr.stack_mem = NULL;
	attr.stack_size = 10240;
	attr.priority = osPriorityNormal;

	if (osThreadNew((osThreadFunc_t)MQTT_LambTask, NULL, &attr) == NULL)
	{
		printf("[MQTT_Lamb] Falied to create MQTT_LambTask!\n");
	}
}
APP_FEATURE_INIT(MQTT_Lamb);